/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Facades;

import com.dpy.appmvdpy.Models.DefaultModel;
import java.util.List;
import javax.enterprise.inject.spi.Bean;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author ac_psoares
 */
@Repository
public abstract class DefaultFacade<T> {    
  
    protected EntityManager em;    
    private Class<? extends DefaultModel> entityClass;
    
    public DefaultFacade(Class<? extends DefaultModel> entityClass)
    {
       this.entityClass = entityClass;
    }
    
    @PersistenceContext
    public void setEntityManagerFactory(EntityManager entityManagerFactory) {
            this.em = entityManagerFactory;
    }    

    @Transactional
    public void add(T entity)
    {
     // setId(entity);
       em.persist(entity);
       em.flush();
    }      
    
    @Transactional(readOnly=true)
    public T getById(int id)
    {
       return (T) em.find(entityClass, id);
    }
    
    @Transactional(readOnly=true)
    public List<T> listAll(int pag)
    {
       Query q = em.createQuery("SELECT c from " + entityClass.getName() + " as c ");
       q.setFirstResult(pag * 100);
       q.setMaxResults(100);
       return q.getResultList();
    }
    
    @Transactional(readOnly=true)
    public List<T> listAll()
    {
       Query q = em.createQuery("SELECT c from " + entityClass.getName() + " as c ");
       return q.getResultList();
    }
    
    @Transactional
    public int getMaxId()
    {
       Query q = em.createQuery("SELECT max(id) from " + entityClass.getName() + " as c ");
       return q.getSingleResult() != null ? ((Number)q.getSingleResult()).intValue() : 0;    
    }
    
    @Transactional
    public List<T> searchByName(String name)
    {
       return em.createNamedQuery(entityClass.getSimpleName() + ".findByName").setParameter("name", name).getResultList();  
    }
    public abstract void setId(T entity);
    
    @Transactional
    public void edit(T model)
    {
      em.merge(model);
      em.flush();
    }
    
    @Transactional
    public int pageNumbers()
    {
       return (em.createQuery("SELECT c from " + entityClass.getName() + " as c ").getResultList().size() / 100); 
    }
    
    @Transactional
    public void delete(int id)
    {
       T model = getById(id);
       em.remove(model);
       em.flush();   
    }  
}
